


// Plot variables
var googleChart; //Handle to chart
var googleChartData;
var maxVal = 0; //TODO abs of?
var minVal = 100000;

//Zoom variables
var zoomCount = 0;
var startX;
var stopX;


var options = {
    // width: 700,
    height: 440,
    title: '',
    baseTitle: '',
    series: {
            0: { color: '#e2431e' },
            1: { color: '#e7711b' },
            2: { color: '#f1ca3a' },
            3: { color: '#6f9654' },
            4: { color: '#1c91c0' },
            5: { color: '#43459d' },
          },
    chartArea: {
        'width': '75%',
        'height': '90%'
    },
    legend: {
        'position': 'none'
    },
    interpolateNulls: true,
    hAxis: {
        format: 'dd/MM/yyyy',
        viewWindowMode: 'explicit',
        viewWindow: {
            min: 0,
            max: 0
        }
    },
    vAxis: {
        title: "Unit",
        viewWindowMode: 'explicit',
        viewWindow: {
            max: 0,
            min: 0
        }
    }

};

$('#appList').change(function (e) {
    e.preventDefault();

    console.log("New app selected");
    selectAppOptions();
    
    $.ajax({
        url:		'nabtonData.php',
        dataType:	'json',
        success:	setValidDaysHandler,
        error:		errorHandler("Failed to get number of days"),
        type:		'POST',
        data:		{ 
                        action: 'fetchValidDates',
                        appId: $('#appList').val()
                    }
    });

});

$('#datepicked').click(function (e) {
    e.preventDefault();

    console.log("New date selected");
    selectAppOptions();
    var from = $( "#datepicker-1" ).datepicker("getDate");
    var to   = $( "#datepicker-2" ).datepicker("getDate");

    if (to < from)
    {
        alert("Pick a valid date interval")
    }
    else
    {
        to.setHours(23);
        to.setMinutes(59);
        to.setSeconds(59);
        loadChart(from, to);    
    }
});

$("#datepicker-1").datepicker({
       beforeShowDay : function (date)
       {
          return [false];
       },
       defaultDate: new Date()
});


$("#datepicker-2").datepicker({
       beforeShowDay : function (date)
       {
          return [false];
       },
       defaultDate: new Date()
});



//#############################################
//# Function - loadChart() 
//# Description: Called once to initiate and load chart
//#############################################
function loadChart(from, to){
	//Pick currently selected id
    console.log(from + " | " + to);
	var appId      = $('#appList').val();
    var resolution = $('#resolutionList').val();
	console.log("Loading chart for app:"+appId + " res: " + resolution);

	if (appId == null && appId == undefined){
		return;
	}
    
	//Make request to fetch data for sid
	$.ajax({
		url:		'nabtonData.php', 
		dataType:	'json', 
		success:	graphHandler,
		error:		errorHandler,
		type:		'POST', 
		data:		{ 
						action: 'fetchAppData',
						appId: appId,
                        from: from.getTime(),
                        to: to.getTime(),
                        resolution: parseInt(resolution)
					}
	});	
    
    //Populate selection input in form 
    function graphHandler(data){
        console.log('graphHandler - called');
        var dataPoints = 0;
        
        if (data != null)
        {
            //All data:
            //console.log("All data:");
            //console.log(data);
           
            dataLength=data.length;
            dataPoints = data[data.length-1];
            data.splice(-1, 1);
            dataLength = dataLength -1;
            
            var dataX=data[0];
            
            for (ii=2; ii<dataLength; ii=ii+2) 
            {
                dataX = dataX.concat(data[ii]);
            }
            
            dataX = $.unique(dataX).sort();
            //console.log("Time data");
            console.log(dataX);
            
            var maxVal = -1000000; //TODO abs of?
            var minVal = 1000000;
                
            
            var curr_index=[];
            for (ii=0; ii<dataLength/2; ii++) 
            {
                curr_index[ii]=0;
            }
            
            var final = [];
            for (ii=0; ii<dataX.length; ii++) //loop through x (time)
            {
                final[ii] = [];
                final[ii][0]=new Date(dataX[ii]*1000);
                for (jj=0; jj<dataLength; jj=jj+2)  //loop through the sids' x (time)
                {
                    
                    if (dataX[ii]==data[jj][curr_index[jj/2]]) 
                    {
                        final[ii][jj/2+1]=data[jj+1][curr_index[jj/2]];
                        curr_index[jj/2]++;
                          
                        // Get max and min values
                        if (final[ii][jj/2+1]<minVal) 
                        {
                            minVal = final[ii][jj/2+1];
                        }
                        else if (final[ii][jj/2+1]>maxVal) 
                        {
                            maxVal = final[ii][jj/2+1];
                        } 
                          
                    }
                    else 
                    {
                        final[ii][jj/2+1]=null;
                    }
                }
                
            }            

            console.log("max:"+maxVal+" min:"+minVal);

            //===Select chartType 
            if(currentAppData[2] == 1)
            {
                //Line type
                googleChart = new google.visualization.ColumnChart(
                                document.getElementById('chartDiv'));
            }
            else 
            {
                //Defaults to line (0)
                googleChart = new google.visualization.LineChart(
                                document.getElementById('chartDiv'));
            }
            
            //== Check that the final data is not null
            if (final != null)
            {
                google.visualization.events.addListener(googleChart, 'select', zoomHandler);
                googleChartData = new google.visualization.DataTable();
                // Declare columns
                googleChartData.addColumn('datetime');
                for(i=0; i<dataLength/2; i++)
                {
                     googleChartData.addColumn('number');
                }
             
                // Add data to 
                for(i=0; i<final.length; i++)
                {
                    googleChartData.addRow(final[i]);
                }

                var formatter = new google.visualization.DateFormat({
                    pattern: "dd/MM kk:mm:ss"
                });
                // Reformat data.
                formatter.format(googleChartData, 0);
                //Change chart options - Like title, axis names etc
                options.hAxis.viewWindow.min = final[0][0];
                options.hAxis.viewWindow.max = final[dataX.length-1][0];

                options.vAxis.viewWindow.min = minVal;
                options.vAxis.viewWindow.max = maxVal;
                
                //For print of total number of data points used
                var accValues = dataPoints[0];
                for (i = 1; i < dataPoints.length; i++)
                    accValues = accValues + ", " +  dataPoints[i];
                
                options.title = currentAppData[1] + " (" + accValues + ")";
                googleChart.draw(googleChartData, options);
                
                
                //#############################################
                //# Function - zoomhandle() 
                //# Description: Called when user clicks in plot. Click two times and update chart
                //#############################################
                function zoomHandler() {
                    var selectedItem = googleChart.getSelection()[0];
                    if (selectedItem) {
                        // Determine if user clicks first or second time
                        if (zoomCount == 0) 
                        {
                            startX = googleChartData.getValue(selectedItem.row, 0);
                            zoomCount = 1;
                        }
                        else if (zoomCount == 1)
                        {
                            stopX = googleChartData.getValue(selectedItem.row, 0);
                            zoomCount = 0;
                            
                            //Check in which order user has selected the interval
                            if (stopX < startX)
                                loadChart(stopX, startX);
                            else
                                loadChart(startX, stopX);
                        }
                    }
                }
                
            }
        }
        else
        {
            console.log("No data available for date: \n" + from);
        }
    }
}

//#############################################
//# Function - selectAppOptions() 
//# Description: Called when selecting sid to show in graph
//#############################################
function selectAppOptions()
{
    var appId = $('#appList').val();
    for (i = 0; i < appDataArray.length; i++) 
    {
        if (appDataArray[i][0] == appId)
        {
            currentAppData = appDataArray[i];
        }
    }
}

function arrayUnique(array) {
    var a = array.concat();
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++j) {
            if(a[i] === a[j])
                a.splice(j--, 1);
        }
    }

    return a;
};



		